package com.yunding.house.utils.wx.utils;
import com.jfinal.kit.PropKit;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * ClassName:SigUtils
 *
 * @Description: 验证接入
 * @Author:chenzhen Date:2019/3/26 13:05
 * Version 1.0
 **/
public class SigUtils {
    //设置接入的token数据
    private static String token = "ythhtml";

    /**
     * 验证
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
//        PropKit.use("javen_config.txt");

        //1.将token、timestamp、nonce三个参数进行字典序排序
//        String[] aar = new String[]{PropKit.get("token"), timestamp, nonce};
        String[] aar = new String[]{token, timestamp, nonce};
        Arrays.sort(aar);

        //2.将三个参数字符串拼接成一个字符串进行sha1加密
        String content = aar[0] + aar[1] + aar[2];
        String mysig = sha1(content);

        System.out.println("123="+mysig);
        //开发者获得加密后的字符串可与signature对比
        if (mysig.equalsIgnoreCase(signature)) {
            return true;
        }
        return false;

    }

    /**
     * 进行sha1加密操作
     * @param str
     * @return
     */
    private static String sha1(String str) {
        try {
            //获取加密方式
            MessageDigest md = MessageDigest.getInstance("sha1");
            //转换为字符数组
            byte[] digest = md.digest(str.getBytes());
            char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            StringBuilder sb = new StringBuilder();
            //将字节转换为十六进制字符串
            for (byte b : digest) {
                sb.append(chars[b >> 4 & 15]);    //??4λ??????
                sb.append(chars[b & 15]);    //??4λ??????
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
